<template>
  <text class="c-number" v-if="props.value != null" :class="{ 'c-mini': precisionMini }">
    <text v-if="prefix" :class="{ 'c-number-prefix': prefixMini }">{{ prefix }}</text>
    <text>{{ valueInt }}</text>
    <text class="c-number-mini">{{ valueDecimal }}</text>
    <text :class="{ 'c-number-suffix': prefixMini }">{{ isY ? '亿' : isW ? '万' : '' }}{{ suffix }}</text>
  </text>
</template>
<script setup>
import { Text } from '@tarojs/components';
import { computed } from 'vue';

const props = defineProps({
  value: Number,
  autoChange: {
    type: Boolean,
    default: false
  },
  precision: Number,
  kilobit: {
    type: Boolean,
    default: true
  },
  precisionMini: {
    type: Boolean,
    default: false
  },
  suffixMini: {
    type: Boolean,
    default: true
  },
  prefixMini: {
    type: Boolean,
    default: true
  },
  prefix: String,
  suffix: String
});
const isY = computed(() => (props.autoChange ? props.value >= 10 ** 8 : false));

const isW = computed(() => (props.autoChange ? props.value >= 10 ** 5 : false));

const currentValue = computed(() => (props.value || 0) / (isY.value ? 100000000 : isW.value ? 10000 : 1));

const valueDecimal = computed(() => {
  let value = currentValue.value;
  if (typeof value != 'number') {
    value = Number(value);
  }
  let [int, dec] = (value || 0).toString().split('.');
  if (props.precision != null) {
    return '.' + value.toFixed(props.precision).split('.')[1];
  }
  if (!dec) return '';
  return '.' + dec.substring(0, props.precision);
});

const valueInt = computed(() => {
  var result = [];
  var counter = 0;
  let num = parseInt(currentValue.value).toString().split('');
  for (var i = num.length - 1; i >= 0; i--) {
    counter++;
    result.unshift(num[i]);
    if (props.kilobit)
      if (!(counter % 3) && i != 0) {
        result.unshift(',');
      }
  }
  return result.join('');
});
</script>
<style lang="scss">
.c-number {
  position: relative;
  &.c-mini .c-number-mini {
    font-size: 0.8em;
  }
  .c-number-suffix,
  .c-number-prefix {
    font-size: 0.8em;
  }
}
</style>
